//
//  BIDMyHouseViewController.m
//  HJGJCommunity
//
//  Created by mal on 2017/5/19.
//  Copyright © 2017年 mal. All rights reserved.
//

#import "BIDMyHouseViewController.h"
#import "BIDBindingHouseViewController.h"
#import "BIDPickerMenuView.h"
#import "BIDHouseBinderCell.h"
#import <SDWebImage/UIImageView+WebCache.h>

//获取我名下绑定的房产列表
static NSString *myHouseListURL = @"memberHouseAndroid/list.action";

//获取某套房屋下已经绑定过的人员列表（只对业主有用）
static NSString *houseBinderListURL = @"memberHouseAndroid/listHouseMember.action";

//检查输入的手机号与业主预留的手机号是否相同
static NSString *checkPhoneIsHouseHolderURL = @"memberHouseAndroid/checkHouseHolder.action";

//解除绑定
static NSString *unbindingHouseURL = @"memberHouseAndroid/removeBindHouseMember.action";

//修改住户角色(0-未设置, 1-业主，2-租客，3-家人)
static NSString *editRoleTypeURL = @"memberAndroid/modify.action";

@interface BIDMyHouseViewController ()<UITableViewDelegate, UITableViewDataSource, BIDPickerMenuViewDelegate, BIDHouseBinderCellDelegate>
{
    //我名下绑定的房屋
    NSMutableArray *_myHouseArr;
    //某个房子下绑定的人员
    NSMutableArray *_houseBinderArr;
    //用来显示我名下已绑定的房屋
    BIDPickerMenuView *_pickerMenuView;
    //当前选中房屋的名字和房屋编码、房屋id
    NSString *_houseName;
    NSString *_houseCode;
    NSString *_houseId;
    
    BOOL _bRegister;
    UIAlertController *_alert;
    //某套房屋下某个绑定人的角色
    NSString *_roleType;
    //
    NSUInteger _editRow;
}
@end

@implementation BIDMyHouseViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.
    self.title = @"我的房产";
    [self.view setBackgroundColor:RGBACOLOR(230.f, 230.f, 237.f, 1.f)];
    _myHouseArr = [NSMutableArray array];
    _houseBinderArr = [NSMutableArray array];
    _tableView.hidden = YES;
    _unbindingHouseBtn.hidden = YES;
    [_tableView setBackgroundColor:[UIColor clearColor]];
    _tableView.tableFooterView = [[UIView alloc] init];
    _tableView.allowsSelection = NO;
    //
    [self createActionSheet];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];

    [self fetchMyHouseList];
}
- (void)createActionSheet
{
    //创建actionSheet
    _alert = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction *action){
    }];
    UIAlertAction *action1 = [UIAlertAction actionWithTitle:@"租客" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        [self editRoleTypeWithType:@"2"];
    }];
    UIAlertAction *action2 = [UIAlertAction actionWithTitle:@"家人" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        [self editRoleTypeWithType:@"3"];
    }];
    UIAlertAction *action3 = [UIAlertAction actionWithTitle:@"业主" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action){
        [self editRoleTypeWithType:@"1"];
    }];
    [_alert addAction:cancelAction];
    [_alert addAction:action1];
    [_alert addAction:action2];
    [_alert addAction:action3];
}

/**
 获取当前用户名下的房产
 */
- (void)fetchMyHouseList
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], myHouseListURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"memberId=%@", [AppDelegate getUserId]];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            _houseCodeTF.placeholder = @"尚未绑定房屋";
        }
        else
        {
            _myHouseArr = responseDic[@"rows"];
            NSMutableArray *arr = [NSMutableArray array];
            for(NSDictionary *dic in _myHouseArr)
            {
                [arr addObject:dic[@"address"]];
            }
            if(_pickerMenuView)
            {
                [_pickerMenuView updateDataSourceWithArr:arr];
            }
            else
            {
                _pickerMenuView = [[BIDPickerMenuView alloc] initWithMenuArr:arr];
                _pickerMenuView.delegate = self;
                _pickerMenuView.bIsInputView = YES;
                _houseCodeTF.inputView = _pickerMenuView;
            }
            //
            if(_myHouseArr.count > 0)
            {
                [AppDelegate setBindingHouse:_myHouseArr];
                NSDictionary *dic = _myHouseArr[0];
                _houseId = dic[@"id"];
                _houseName = dic[@"address"];
                _houseCode = dic[@"houseCode"];
                _houseCodeTF.text = _houseName;
                //验证当前用户是否是该房屋的业主
                [self checkIsHouseHolder];
            }
            else
            {
                //名下没有绑定的房屋
                [AppDelegate setBindingHouse:@[]];
                _houseId = @"";
                _houseName = @"";
                _houseCode = @"";
                _houseCodeTF.placeholder = @"尚未绑定房屋";
            }
        }
    }];
}

/**
 显示当前用户名下绑定的房产列表

 @param sender <#sender description#>
 */
- (IBAction)showMyHouseListBtnHandler:(id)sender
{
    if(_myHouseArr.count > 0)
    {
        [_houseCodeTF becomeFirstResponder];
    }
}

/**
 去绑定房产

 @param sender <#sender description#>
 */
- (IBAction)bindingHouseBtnHandler:(id)sender
{
    BIDBindingHouseViewController *vc = [[BIDBindingHouseViewController alloc] initWithNibName:@"BIDBindingHouseViewController" bundle:nil];
    UINavigationController *nav = [[UINavigationController alloc] initWithRootViewController:vc];
    [self setNavigationControllerAttribute:nav];
    [self presentViewController:nav animated:YES completion:^{}];
}

/**
 解除绑定

 @param sender <#sender description#>
 */
- (IBAction)unbindingHouseBtnHandler:(id)sender
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], unbindingHouseURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"memberId=%@&searchParam.houseCode=%@", [AppDelegate getUserId], _houseCode];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            [self showHint:@"解除绑定成功"];
            [self fetchMyHouseList];
        }
    }];
}
/**
 *设置UINavigationController的属性
 */
- (void)setNavigationControllerAttribute:(UINavigationController *)navController
{
    [navController.navigationBar setBackgroundImage:[UIImage imageNamed:@"navBarBg.png"] forBarMetrics:UIBarMetricsDefault];
    NSDictionary *attributeDictionary = @{NSFontAttributeName:[UIFont systemFontOfSize:22.0f], NSForegroundColorAttributeName:[UIColor whiteColor]};
    [navController.navigationBar setTitleTextAttributes:attributeDictionary];
    [navController.navigationBar setTintColor:[UIColor whiteColor]];
}

/**
 验证当前用户是否是当前房屋的业主
 */
- (void)checkIsHouseHolder
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], checkPhoneIsHouseHolderURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"memberId=%@&memberHouse.telephone=%@&memberHouse.houseCode=%@", [AppDelegate getUserId], [AppDelegate getUserName], _houseCode];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            //当前用户不是业主
            _unbindingHouseBtn.hidden = NO;
        }
        else
        {
            _unbindingHouseBtn.hidden = YES;
            //如果是业主，则获取该房屋下绑定的人员列表
            [self fetchHouseBinderList];
        }
    }];
}

/**
 获取该房屋下绑定的人员列表
 */
- (void)fetchHouseBinderList
{
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], houseBinderListURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"memberId=%@&searchParam.houseCode=%@", [AppDelegate getUserId], _houseCode];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(id obj, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:@"获取已绑定房屋信息失败" buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            if([obj isKindOfClass:[NSArray class]])
            {
                _houseBinderArr = [[NSMutableArray alloc] initWithArray:(NSArray *)obj];
                _tableView.hidden = NO;
                [_tableView reloadData];
            }
        }
    }];
}

/**
 修改某住户对于某套房屋的角色

 @param type <#type description#>
 */
- (void)editRoleTypeWithType:(NSString *)type
{
    if([type isEqualToString:_roleType])
    {}
    else
    {
        NSDictionary *dic = _houseBinderArr[_editRow];
        NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], editRoleTypeURL];
        NSString *strPost = [[NSString alloc] initWithFormat:@"memberId=%@&memberDetail.property=%@&memberDetail.memberId=%@", [AppDelegate getUserId], type, dic[@"memberId"]];
        [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
            if(errMsg)
            {
                [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
            }
            else
            {
                [self showHint:@"修改角色成功"];
                [self fetchHouseBinderList];
            }
        }];
    }
}

#pragma mark - BIDPickerMenuViewDelegate
- (void)chooseMenuAtIndex:(NSUInteger)index
{
    NSDictionary *dic = _myHouseArr[index];
    _houseCode = dic[@"houseCode"];
    _houseName = dic[@"address"];
    _houseId = dic[@"id"];
    _houseCodeTF.text = _houseName;
    [self checkIsHouseHolder];
}

#pragma mark - BIDHouseBinderCellDelegate
- (void)unbindingAtRow:(NSUInteger)row
{
    NSDictionary *dic = _houseBinderArr[row];
    NSString *strRequestURL = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], unbindingHouseURL];
    NSString *strPost = [[NSString alloc] initWithFormat:@"memberId=%@&searchParam.houseCode=%@", dic[@"memberId"], _houseCode];
    [self sendHttpRequestWithURL:strRequestURL postData:strPost withCompletion:^(NSDictionary *responseDic, NSString *errMsg){
        if(errMsg)
        {
            [self showAlertView:errMsg buttonTitle:ALERT_BTN_TITLE tag:0 functionName:nil];
        }
        else
        {
            [self showHint:@"解除绑定成功"];
            [_houseBinderArr removeObject:dic];
            [_tableView reloadData];
        }
    }];
}

/**
 修改住户角色

 @param row <#row description#>
 */
- (void)editRoleTypeAtRow:(NSUInteger)row
{
    _editRow = row;
    NSDictionary *dic = _houseBinderArr[row];
    _roleType = [[NSString alloc] initWithFormat:@"%@", dic[@"property"]];
    if(_alert)
    {
        [self presentViewController:_alert animated:YES completion:^{}];
    }
}

#pragma mark - UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return _houseBinderArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = nil;
    static NSString *identifier = @"identifier";
    NSUInteger row = indexPath.row;
    if(!_bRegister)
    {
        _bRegister = YES;
        UINib *nib = [UINib nibWithNibName:@"BIDHouseBinderCell" bundle:nil];
        [tableView registerNib:nib forCellReuseIdentifier:identifier];
    }
    BIDHouseBinderCell *houseBinderCell = [tableView dequeueReusableCellWithIdentifier:identifier];
    houseBinderCell.row = row;
    houseBinderCell.delegate = self;
    NSDictionary *dic = _houseBinderArr[row][@"memberDetail"];
    NSString *strNickName = dic[@"nickName"];
    if(ISNULL(strNickName)) strNickName = dic[@"userName"];
    NSString *strPropertyName = dic[@"propertyName"];
    NSString *strTitle = [[NSString alloc] initWithFormat:@"%@ %@", strNickName, strPropertyName];
    NSMutableAttributedString *strAttributeTitle = [[NSMutableAttributedString alloc] initWithString:strTitle];
    [strAttributeTitle addAttribute:NSForegroundColorAttributeName value:[UIColor darkGrayColor] range:NSMakeRange(strNickName.length+1, strPropertyName.length)];
    [strAttributeTitle addAttribute:NSFontAttributeName value:[UIFont systemFontOfSize:13.f] range:NSMakeRange(strNickName.length+1, strPropertyName.length)];
    houseBinderCell.titleLabel.attributedText = strAttributeTitle;
    houseBinderCell.phoneLabel.text = [[NSString alloc] initWithFormat:@"手机号码:%@", dic[@"userName"]];
    NSString *strDate = dic[@"createTime"];
    NSArray *arr = [strDate componentsSeparatedByString:@" "];
    houseBinderCell.dateLabel.text = [[NSString alloc] initWithFormat:@"注册日期:%@", arr[0]];
    NSString *strAvatarPath = [[NSString alloc] initWithFormat:@"%@/%@", [AppDelegate getServerAddr], dic[@"photo"]];
    [houseBinderCell.imgView setImageWithURL:[NSURL URLWithString:strAvatarPath] placeholderImage:[UIImage imageNamed:@"default_portrait.png"]];
    cell = houseBinderCell;
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 74.f;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    UIView *headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, CGRectGetWidth(tableView.frame), 30.f)];
    [headerView setBackgroundColor:[UIColor clearColor]];
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(10.f, 0.f, 200.f, 21.f)];
    [label setTextColor:[UIColor darkGrayColor]];
    [label setFont:[UIFont systemFontOfSize:15.f]];
    [label setText:@"已绑定此房屋的人员"];
    [headerView addSubview:label];
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30.f;
}

@end
